<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>细胞进化 - 第一阶段：白板细胞</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: #1a1a2e;
            color: #fff;
            overflow: hidden;
        }

        .game-container {
            position: relative;
            width: 100vw;
            height: 100vh;
            background: radial-gradient(circle at center, #1a1a2e 0%, #16213e 50%, #0f3460 100%);
            overflow: hidden;
        }

        .cell-boundary {
            position: absolute;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            pointer-events: none;
            animation: pulse 4s ease-in-out infinite;
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); opacity: 0.3; }
            50% { transform: scale(1.02); opacity: 0.6; }
        }

        #game-canvas {
            position: absolute;
            top: 0;
            left: 0;
            background: transparent;
            cursor: pointer;
        }

        .ui-panel {
            position: absolute;
            top: 20px;
            left: 20px;
            background: rgba(0, 0, 0, 0.7);
            padding: 15px;
            border-radius: 10px;
            min-width: 250px;
        }

        .status-bar {
            margin-bottom: 10px;
        }

        .status-label {
            display: inline-block;
            width: 80px;
            font-size: 12px;
        }

        .energy-bar, .volume-bar {
            display: inline-block;
            width: 120px;
            height: 15px;
            background: rgba(255, 255, 255, 0.2);
            border-radius: 7px;
            overflow: hidden;
            vertical-align: middle;
        }

        .energy-fill {
            height: 100%;
            background: linear-gradient(90deg, #ff6b6b, #ffa500);
            transition: width 0.3s;
        }

        .volume-fill {
            height: 100%;
            background: linear-gradient(90deg, #4ecdc4, #44a08d);
            transition: width 0.3s;
        }

        .stats {
            font-size: 12px;
            margin-bottom: 5px;
        }

        .instructions {
            position: absolute;
            bottom: 20px;
            left: 20px;
            background: rgba(0, 0, 0, 0.7);
            padding: 15px;
            border-radius: 10px;
            max-width: 400px;
        }

        .particle-info {
            position: absolute;
            top: 20px;
            right: 20px;
            background: rgba(0, 0, 0, 0.7);
            padding: 15px;
            border-radius: 10px;
            max-width: 250px;
            display: none;
        }

        .particle-type {
            margin-bottom: 8px;
            padding: 5px;
            border-radius: 5px;
            font-size: 12px;
        }

        .rna { background: rgba(0, 123, 255, 0.3); border-left: 3px solid #007bff; }
        .amino { background: rgba(40, 167, 69, 0.3); border-left: 3px solid #28a745; }
        .energy { background: rgba(255, 193, 7, 0.3); border-left: 3px solid #ffc107; }
        .lipid { background: rgba(108, 117, 125, 0.3); border-left: 3px solid #6c757d; }
        .enzyme { background: rgba(220, 53, 69, 0.3); border-left: 3px solid #dc3545; }
        .intermediate { background: rgba(139, 69, 193, 0.3); border-left: 3px solid #8b45c3; }

        .reaction-hint {
            position: absolute;
            background: rgba(0, 0, 0, 0.8);
            padding: 10px;
            border-radius: 8px;
            font-size: 14px;
            display: none;
            z-index: 1000;
            pointer-events: none;
        }

        .reaction-progress {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(40, 167, 69, 0.9);
            padding: 20px;
            border-radius: 15px;
            display: none;
            z-index: 1000;
        }

        .dragging {
            cursor: grabbing !important;
            z-index: 1000;
        }

        .bubble {
            position: absolute;
            border-radius: 50%;
            background: rgba(255, 255, 255, 0.1);
            animation: float 3s ease-in-out infinite;
        }

        @keyframes float {
            0%, 100% { transform: translateY(0px) scale(1); opacity: 0.3; }
            50% { transform: translateY(-20px) scale(1.1); opacity: 0.6; }
        }

        .particle-count {
            font-size: 10px;
            text-align: center;
            margin-top: 3px;
        }

        .game-title {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            color: rgba(255, 255, 255, 0.8);
            font-size: 24px;
            z-index: -1;
            pointer-events: none;
        }
    </style>
</head>
<body>
    <div class="game-container">
        <canvas id="game-canvas"></canvas>

        <div class="ui-panel">
            <div class="status-bar">
                <span class="status-label">能量:</span>
                <div class="energy-bar">
                    <div class="energy-fill" id="energy-fill"></div>
                </div>
            </div>
            <div class="status-bar">
                <span class="status-label">体积:</span>
                <div class="volume-bar">
                    <div class="volume-fill" id="volume-fill"></div>
                </div>
            </div>
            <div class="stats" id="stats">
                RNA: 0 | 氨基酸: 0 | 能量物质: 0
            </div>
        </div>

        <div class="particle-info" id="particle-info">
            <div class="particle-type rna">🔵 RNA片段: 遗传信息载体</div>
            <div class="particle-type amino">🟢 氨基酸: 蛋白质合成原料</div>
            <div class="particle-type energy">🟡 能量物质: 维持细胞活动</div>
            <div class="particle-type lipid">⚪ 脂质分子: 细胞膜组成</div>
            <div class="particle-type enzyme">🔴 酶分子: 催化各种反应</div>
            <div class="particle-type intermediate">🟣 中间产物: 反应中间体</div>
        </div>

        <div class="reaction-hint" id="reaction-hint">
            <div id="reaction-text">将合适物质放在一起...</div>
        </div>

        <div class="reaction-progress" id="reaction-progress">
            <div id="progress-text">反应进行中...</div>
            <div id="progress-bar" style="width: 200px; height: 10px; background: rgba(255,255,255,0.2); border-radius: 5px; margin-top: 10px;">
                <div id="progress-fill" style="height: 100%; width: 0%; background: #28a745; border-radius: 5px; transition: width 0.1s;"></div>
            </div>
        </div>

        <div class="cell-boundary" id="cell-boundary"></div>

        <div class="instructions">
            <h3>玩法说明：</h3>
            <p>• 拖拽物质颗粒移动位置</p>
            <p>• 将合适物质放在一起触发生化反应</p>
            <p>• RNA + 酶 + 氨基酸 = 蛋白质</p>
            <p>• 管理细胞内部空间和物质平衡</p>
        </div>

        <div class="game-title">
            <h1>细胞进化 第一阶段</h1>
            <p>白板细胞的起源之旅</p>
        </div>
    </div>

    <script>
        class Game {
            constructor() {
                this.canvas = document.getElementById('game-canvas');
                this.ctx = this.canvas.getContext('2d');
                this.resizeCanvas();

                // 细胞参数
                this.cellCenterX = this.canvas.width / 2;
                this.cellCenterY = this.canvas.height / 2;
                this.cellRadius = Math.min(this.canvas.width, this.canvas.height) * 0.4;

                // 物质粒子
                this.particles = [];
                this.maxParticles = 60; // 更拥挤
                this.draggedParticle = null;
                this.dragOffset = { x: 0, y: 0 };

                // 收集统计
                this.collected = {
                    rna: 0,
                    amino: 0,
                    energy: 0,
                    lipid: 0,
                    enzyme: 0,
                    intermediate: 0
                };

                // 反应系统
                this.reactions = [];
                this.currentReaction = null;

                // 动画和交互
                this.animationId = null;
                this.isRunning = true;
                this.lastTime = 0;

                this.setupEventListeners();
                this.createInitialParticles();
                this.setupCellBoundary();
                this.startGameLoop();
            }

            resizeCanvas() {
                this.canvas.width = window.innerWidth;
                this.canvas.height = window.innerHeight;
            }

            setupEventListeners() {
                window.addEventListener('resize', () => {
                    this.resizeCanvas();
                    this.cellCenterX = this.canvas.width / 2;
                    this.cellCenterY = this.canvas.height / 2;
                    this.cellRadius = Math.min(this.canvas.width, this.canvas.height) * 0.4;
                    this.setupCellBoundary();
                });

                // 鼠标事件
                this.canvas.addEventListener('mousedown', (e) => this.handleMouseDown(e));
                this.canvas.addEventListener('mousemove', (e) => this.handleMouseMove(e));
                this.canvas.addEventListener('mouseup', () => this.handleMouseUp());

                // 显示粒子信息
                document.getElementById('particle-info').style.display = 'block';
            }

            handleMouseDown(e) {
                const rect = this.canvas.getBoundingClientRect();
                const mouseX = e.clientX - rect.left;
                const mouseY = e.clientY - rect.top;

                // 检查是否点击了粒子
                for (let particle of this.particles) {
                    const dx = mouseX - particle.x;
                    const dy = mouseY - particle.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);

                    if (distance < particle.radius) {
                        this.draggedParticle = particle;
                        this.dragOffset.x = dx;
                        this.dragOffset.y = dy;
                        particle.isDragging = true;
                        this.canvas.style.cursor = 'grabbing';
                        break;
                    }
                }
            }

            handleMouseMove(e) {
                if (!this.draggedParticle) return;

                const rect = this.canvas.getBoundingClientRect();
                const mouseX = e.clientX - rect.left;
                const mouseY = e.clientY - rect.top;

                // 更新拖拽粒子的位置
                this.draggedParticle.x = mouseX - this.dragOffset.x;
                this.draggedParticle.y = mouseY - this.dragOffset.y;

                // 限制在细胞内部
                const dx = this.draggedParticle.x - this.cellCenterX;
                const dy = this.draggedParticle.y - this.cellCenterY;
                const distance = Math.sqrt(dx * dx + dy * dy);

                if (distance > this.cellRadius - this.draggedParticle.radius) {
                    const angle = Math.atan2(dy, dx);
                    this.draggedParticle.x = this.cellCenterX + Math.cos(angle) * (this.cellRadius - this.draggedParticle.radius);
                    this.draggedParticle.y = this.cellCenterY + Math.sin(angle) * (this.cellRadius - this.draggedParticle.radius);
                }

                this.checkReactions();
            }

            handleMouseUp() {
                if (this.draggedParticle) {
                    this.draggedParticle.isDragging = false;
                    this.draggedParticle = null;
                    this.canvas.style.cursor = 'default';
                    this.hideReactionHint();
                }
            }

            createInitialParticles() {
                for (let i = 0; i < this.maxParticles; i++) {
                    this.createParticle();
                }
            }

            createParticle() {
                const types = ['rna', 'amino', 'energy', 'lipid', 'enzyme', 'intermediate'];
                const type = types[Math.floor(Math.random() * types.length)];

                // 在细胞内部随机生成位置
                let x, y;
                do {
                    const angle = Math.random() * Math.PI * 2;
                    const distance = Math.random() * (this.cellRadius - 20);
                    x = this.cellCenterX + Math.cos(angle) * distance;
                    y = this.cellCenterY + Math.sin(angle) * distance;
                } while (this.checkParticleOverlap(x, y, 8));

                const particle = {
                    x: x,
                    y: y,
                    vx: (Math.random() - 0.5) * 0.5, // 更慢的移动
                    vy: (Math.random() - 0.5) * 0.5,
                    radius: Math.random() * 6 + 6, // 稍微大一点
                    type: type,
                    isDragging: false,
                    value: Math.random() > 0.3 ? 1 : 0, // 70%有效，30%无效
                    id: Date.now() + Math.random(),
                    lastCollision: 0
                };

                this.particles.push(particle);
                this.collected[type]++;
                this.updateUI();
            }

            checkParticleOverlap(x, y, radius) {
                for (let particle of this.particles) {
                    const dx = x - particle.x;
                    const dy = y - particle.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    if (distance < radius + particle.radius) {
                        return true;
                    }
                }
                return false;
            }

            setupCellBoundary() {
                const boundary = document.getElementById('cell-boundary');
                boundary.style.width = this.cellRadius * 2 + 'px';
                boundary.style.height = this.cellRadius * 2 + 'px';
                boundary.style.left = (this.cellCenterX - this.cellRadius) + 'px';
                boundary.style.top = (this.cellCenterY - this.cellRadius) + 'px';
            }

            checkReactions() {
                if (!this.draggedParticle) return;

                const nearbyParticles = this.findNearbyParticles(this.draggedParticle, 50);

                // 检查可能的反应
                const reaction = this.checkPossibleReaction(this.draggedParticle, nearbyParticles);

                if (reaction) {
                    this.showReactionHint(reaction);
                } else {
                    this.hideReactionHint();
                }
            }

            findNearbyParticles(centerParticle, radius) {
                const nearby = [];
                for (let particle of this.particles) {
                    if (particle === centerParticle) continue;

                    const dx = particle.x - centerParticle.x;
                    const dy = particle.y - centerParticle.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);

                    if (distance <= radius) {
                        nearby.push({ particle, distance });
                    }
                }
                return nearby;
            }

            checkPossibleReaction(draggedParticle, nearbyParticles) {
                // 蛋白质合成：RNA + 酶 + 氨基酸
                if (draggedParticle.type === 'rna') {
                    const hasEnzyme = nearbyParticles.some(p => p.particle.type === 'enzyme');
                    const hasAmino = nearbyParticles.some(p => p.particle.type === 'amino');
                    if (hasEnzyme && hasAmino) {
                        return {
                            type: 'protein_synthesis',
                            description: '蛋白质合成反应',
                            reactants: ['rna', 'enzyme', 'amino'],
                            product: 'protein'
                        };
                    }
                }

                // 能量转换：葡萄糖 + 酶
                if (draggedParticle.type === 'energy') {
                    const hasEnzyme = nearbyParticles.some(p => p.particle.type === 'enzyme');
                    if (hasEnzyme) {
                        return {
                            type: 'energy_conversion',
                            description: '能量转换反应',
                            reactants: ['energy', 'enzyme'],
                            product: 'atp'
                        };
                    }
                }

                // RNA复制：RNA + 酶
                if (draggedParticle.type === 'rna') {
                    const hasEnzyme = nearbyParticles.some(p => p.particle.type === 'enzyme');
                    if (hasEnzyme && nearbyParticles.length >= 2) {
                        return {
                            type: 'rna_replication',
                            description: 'RNA复制反应',
                            reactants: ['rna', 'enzyme'],
                            product: 'new_rna'
                        };
                    }
                }

                return null;
            }

            showReactionHint(reaction) {
                const hint = document.getElementById('reaction-hint');
                const text = document.getElementById('reaction-text');

                text.textContent = reaction.description;
                hint.style.display = 'block';
                hint.style.left = this.draggedParticle.x + 20 + 'px';
                hint.style.top = this.draggedParticle.y - 30 + 'px';
            }

            hideReactionHint() {
                document.getElementById('reaction-hint').style.display = 'none';
            }

            updateParticles(deltaTime) {
                this.particles.forEach((particle, index) => {
                    if (particle.isDragging) return;

                    // 应用扩散运动
                    particle.x += particle.vx * deltaTime * 0.1;
                    particle.y += particle.vy * deltaTime * 0.1;

                    // 边界碰撞
                    const dx = particle.x - this.cellCenterX;
                    const dy = particle.y - this.cellCenterY;
                    const distance = Math.sqrt(dx * dx + dy * dy);

                    if (distance > this.cellRadius - particle.radius) {
                        const angle = Math.atan2(dy, dx);
                        particle.x = this.cellCenterX + Math.cos(angle) * (this.cellRadius - particle.radius);
                        particle.y = this.cellCenterY + Math.sin(angle) * (this.cellRadius - particle.radius);

                        // 反弹
                        particle.vx *= -0.5;
                        particle.vy *= -0.5;
                    }

                    // 粒子间碰撞
                    this.handleParticleCollisions(particle, index);

                    // 添加随机扰动
                    particle.vx += (Math.random() - 0.5) * 0.01;
                    particle.vy += (Math.random() - 0.5) * 0.01;

                    // 限制速度
                    const speed = Math.sqrt(particle.vx * particle.vx + particle.vy * particle.vy);
                    if (speed > 1) {
                        particle.vx = (particle.vx / speed) * 1;
                        particle.vy = (particle.vy / speed) * 1;
                    }
                });
            }

            handleParticleCollisions(particle, index) {
                for (let i = index + 1; i < this.particles.length; i++) {
                    const other = this.particles[i];
                    if (other.isDragging) continue;

                    const dx = other.x - particle.x;
                    const dy = other.y - particle.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    const minDistance = particle.radius + other.radius;

                    if (distance < minDistance) {
                        // 分离粒子
                        const overlap = minDistance - distance;
                        const separationX = (dx / distance) * overlap * 0.5;
                        const separationY = (dy / distance) * overlap * 0.5;

                        particle.x -= separationX;
                        particle.y -= separationY;
                        other.x += separationX;
                        other.y += separationY;

                        // 交换速度（弹性碰撞）
                        const tempVx = particle.vx;
                        const tempVy = particle.vy;
                        particle.vx = other.vx * 0.8;
                        particle.vy = other.vy * 0.8;
                        other.vx = tempVx * 0.8;
                        other.vy = tempVy * 0.8;
                    }
                }
            }

            createAbsorptionEffect(x, y) {
                const effect = {
                    x: x,
                    y: y,
                    radius: 0,
                    maxRadius: 50,
                    alpha: 1
                };

                const animate = () => {
                    effect.radius += 2;
                    effect.alpha -= 0.05;

                    this.ctx.save();
                    this.ctx.globalAlpha = effect.alpha;
                    this.ctx.beginPath();
                    this.ctx.arc(effect.x, effect.y, effect.radius, 0, Math.PI * 2);
                    this.ctx.strokeStyle = '#fff';
                    this.ctx.lineWidth = 2;
                    this.ctx.stroke();
                    this.ctx.restore();

                    if (effect.alpha > 0) {
                        requestAnimationFrame(animate);
                    }
                };

                animate();
            }

            updateUI() {
                // 更新能量条
                const energyPercent = (this.cell.energy / this.cell.maxEnergy) * 100;
                document.getElementById('energy-fill').style.width = energyPercent + '%';

                // 更新体积条
                const volumePercent = (this.cell.volume / this.cell.maxVolume) * 100;
                document.getElementById('volume-fill').style.width = volumePercent + '%';

                // 更新统计
                document.getElementById('stats').textContent =
                    `RNA: ${this.collected.rna} | 氨基酸: ${this.collected.amino} | 能量: ${this.collected.energy}`;

                // 能量消耗
                if (this.cell.energy <= 0) {
                    this.gameOver();
                }
            }

            gameOver() {
                this.isRunning = false;
                alert('细胞能量耗尽！游戏结束。\n收集统计：\nRNA: ' + this.collected.rna +
                      '\n氨基酸: ' + this.collected.amino +
                      '\n能量物质: ' + this.collected.energy +
                      '\n脂质: ' + this.collected.lipid);
                location.reload();
            }

            drawCell() {
                // 细胞膜
                this.ctx.save();
                this.ctx.globalAlpha = 0.6;
                this.ctx.beginPath();
                this.ctx.arc(this.cell.x, this.cell.y, this.cell.radius, 0, Math.PI * 2);
                this.ctx.fillStyle = '#fff';
                this.ctx.fill();

                // 细胞内部
                this.ctx.beginPath();
                this.ctx.arc(this.cell.x, this.cell.y, this.cell.radius * 0.8, 0, Math.PI * 2);
                this.ctx.fillStyle = 'rgba(173, 216, 230, 0.3)';
                this.ctx.fill();

                // RNA复制酶（蓝色光点）
                this.ctx.beginPath();
                this.ctx.arc(this.cell.x, this.cell.y, 8, 0, Math.PI * 2);
                this.ctx.fillStyle = '#007bff';
                this.ctx.shadowColor = '#007bff';
                this.ctx.shadowBlur = 10;
                this.ctx.fill();
                this.ctx.restore();
            }

            drawParticles() {
                this.particles.forEach(particle => {
                    this.ctx.save();

                    // 根据类型设置颜色和外观
                    let color, emoji;
                    switch (particle.type) {
                        case 'rna':
                            color = '#007bff';
                            emoji = '🔵';
                            break;
                        case 'amino':
                            color = '#28a745';
                            emoji = '🟢';
                            break;
                        case 'energy':
                            color = '#ffc107';
                            emoji = '🟡';
                            break;
                        case 'lipid':
                            color = '#6c757d';
                            emoji = '⚪';
                            break;
                        case 'enzyme':
                            color = '#dc3545';
                            emoji = '🔴';
                            break;
                        case 'intermediate':
                            color = '#8b45c3';
                            emoji = '🟣';
                            break;
                        default:
                            color = '#fff';
                            emoji = '⚪';
                    }

                    // 拖拽状态高亮
                    if (particle.isDragging) {
                        this.ctx.shadowColor = color;
                        this.ctx.shadowBlur = 15;
                    }

                    // 粒子主体
                    this.ctx.beginPath();
                    this.ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
                    this.ctx.fillStyle = color;
                    this.ctx.fill();

                    // 粒子边框
                    this.ctx.beginPath();
                    this.ctx.arc(particle.x, particle.y, particle.radius, 0, Math.PI * 2);
                    this.ctx.strokeStyle = particle.isDragging ? '#fff' : 'rgba(255, 255, 255, 0.3)';
                    this.ctx.lineWidth = particle.isDragging ? 2 : 1;
                    this.ctx.stroke();

                    // 有效性指示器（白色小点表示有效）
                    if (particle.value > 0) {
                        this.ctx.beginPath();
                        this.ctx.arc(particle.x + particle.radius * 0.6, particle.y - particle.radius * 0.6, particle.radius * 0.2, 0, Math.PI * 2);
                        this.ctx.fillStyle = 'rgba(255, 255, 255, 0.9)';
                        this.ctx.fill();
                    }

                    this.ctx.restore();

                    // 显示粒子类型（只在不拖拽时显示）
                    if (!particle.isDragging) {
                        this.ctx.fillStyle = '#fff';
                        this.ctx.font = '12px Arial';
                        this.ctx.textAlign = 'center';
                        this.ctx.fillText(emoji, particle.x, particle.y + particle.radius + 20);
                    }
                });
            }

            updateParticles() {
                this.particles.forEach(particle => {
                    if (particle.isCollected) return;

                    // 粒子移动
                    particle.x += particle.vx;
                    particle.y += particle.vy;

                    // 边界反弹
                    if (particle.x <= 0 || particle.x >= this.canvas.width) {
                        particle.vx *= -1;
                    }
                    if (particle.y <= 0 || particle.y >= this.canvas.height) {
                        particle.vy *= -1;
                    }

                    // 添加一些随机运动
                    particle.vx += (Math.random() - 0.5) * 0.1;
                    particle.vy += (Math.random() - 0.5) * 0.1;

                    // 限制速度
                    const speed = Math.sqrt(particle.vx * particle.vx + particle.vy * particle.vy);
                    if (speed > 3) {
                        particle.vx = (particle.vx / speed) * 3;
                        particle.vy = (particle.vy / speed) * 3;
                    }
                });
            }

            drawBackground() {
                // 细胞内部背景 - 半透明的细胞质
                const gradient = this.ctx.createRadialGradient(
                    this.cellCenterX, this.cellCenterY, 0,
                    this.cellCenterX, this.cellCenterY, this.cellRadius
                );
                gradient.addColorStop(0, 'rgba(173, 216, 230, 0.1)');
                gradient.addColorStop(0.7, 'rgba(173, 216, 230, 0.05)');
                gradient.addColorStop(1, 'rgba(173, 216, 230, 0.01)');

                this.ctx.fillStyle = gradient;
                this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);

                // 细胞膜轮廓
                this.ctx.save();
                this.ctx.strokeStyle = 'rgba(255, 255, 255, 0.2)';
                this.ctx.lineWidth = 2;
                this.ctx.beginPath();
                this.ctx.arc(this.cellCenterX, this.cellCenterY, this.cellRadius, 0, Math.PI * 2);
                this.ctx.stroke();
                this.ctx.restore();

                // 添加细胞内部的微小颗粒流动效果
                for (let i = 0; i < 30; i++) {
                    const angle = Math.random() * Math.PI * 2;
                    const distance = Math.random() * this.cellRadius * 0.8;
                    const x = this.cellCenterX + Math.cos(angle) * distance;
                    const y = this.cellCenterY + Math.sin(angle) * distance;

                    this.ctx.beginPath();
                    this.ctx.arc(x, y, Math.random() * 2 + 1, 0, Math.PI * 2);
                    this.ctx.fillStyle = 'rgba(255, 255, 255, 0.1)';
                    this.ctx.fill();
                }
            }

            gameLoop(currentTime = 0) {
                if (!this.isRunning) return;

                const deltaTime = currentTime - this.lastTime;
                this.lastTime = currentTime;

                // 清除画布
                this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);

                // 绘制背景
                this.drawBackground();

                // 更新和绘制粒子
                if (deltaTime < 100) { // 防止时间跳跃
                    this.updateParticles(deltaTime);
                }
                this.drawParticles();

                // 绘制细胞结构
                this.drawCell();

                // 每秒检查一次反应
                if (Math.random() < 0.016) { // ~1次/秒
                    this.checkOngoingReactions();
                }

                this.animationId = requestAnimationFrame((time) => this.gameLoop(time));
            }

            checkOngoingReactions() {
                // 检查是否有粒子足够接近来触发反应
                for (let i = 0; i < this.particles.length; i++) {
                    const particle1 = this.particles[i];
                    if (particle1.isDragging) continue;

                    for (let j = i + 1; j < this.particles.length; j++) {
                        const particle2 = this.particles[j];
                        if (particle2.isDragging) continue;

                        const dx = particle2.x - particle1.x;
                        const dy = particle2.y - particle1.y;
                        const distance = Math.sqrt(dx * dx + dy * dy);

                        if (distance < particle1.radius + particle2.radius + 10) {
                            const nearbyParticles = [{particle: particle2, distance: distance}];
                            const reaction = this.checkPossibleReaction(particle1, nearbyParticles);
                            if (reaction) {
                                this.triggerReaction(reaction, [particle1, particle2]);
                                return; // 一次只触发一个反应
                            }
                        }
                    }
                }
            }

            triggerReaction(reaction, reactants) {
                // 显示反应进度
                this.showReactionProgress(reaction);

                // 模拟反应时间
                setTimeout(() => {
                    this.completeReaction(reaction, reactants);
                }, 2000);
            }

            showReactionProgress(reaction) {
                const progressDiv = document.getElementById('reaction-progress');
                const textDiv = document.getElementById('progress-text');
                const fillDiv = document.getElementById('progress-fill');

                textDiv.textContent = reaction.description + '进行中...';
                fillDiv.style.width = '0%';
                progressDiv.style.display = 'block';

                // 动画进度条
                let progress = 0;
                const animate = () => {
                    progress += 2;
                    fillDiv.style.width = progress + '%';

                    if (progress < 100) {
                        requestAnimationFrame(animate);
                    }
                };
                animate();

                // 2秒后隐藏
                setTimeout(() => {
                    progressDiv.style.display = 'none';
                }, 2000);
            }

            completeReaction(reaction, reactants) {
                // 移除反应物
                reactants.forEach(particle => {
                    const index = this.particles.indexOf(particle);
                    if (index > -1) {
                        this.particles.splice(index, 1);
                        this.collected[particle.type]--;
                    }
                });

                // 生成产物
                this.createReactionProduct(reaction);

                this.updateUI();
            }

            createReactionProduct(reaction) {
                let productType;
                switch (reaction.type) {
                    case 'protein_synthesis':
                        productType = 'intermediate'; // 蛋白质
                        break;
                    case 'energy_conversion':
                        productType = 'energy'; // ATP
                        break;
                    case 'rna_replication':
                        productType = 'rna'; // 新RNA
                        break;
                    default:
                        productType = 'intermediate';
                }

                // 在反应位置附近创建产物
                const centerX = reactants.reduce((sum, p) => sum + p.x, 0) / reactants.length;
                const centerY = reactants.reduce((sum, p) => sum + p.y, 0) / reactants.length;

                const product = {
                    x: centerX + (Math.random() - 0.5) * 20,
                    y: centerY + (Math.random() - 0.5) * 20,
                    vx: (Math.random() - 0.5) * 0.5,
                    vy: (Math.random() - 0.5) * 0.5,
                    radius: Math.random() * 4 + 8,
                    type: productType,
                    isDragging: false,
                    value: 1,
                    id: Date.now() + Math.random(),
                    lastCollision: 0
                };

                // 确保产物在细胞内部
                const dx = product.x - this.cellCenterX;
                const dy = product.y - this.cellCenterY;
                const distance = Math.sqrt(dx * dx + dy * dy);

                if (distance > this.cellRadius - product.radius) {
                    const angle = Math.atan2(dy, dx);
                    product.x = this.cellCenterX + Math.cos(angle) * (this.cellRadius - product.radius);
                    product.y = this.cellCenterY + Math.sin(angle) * (this.cellRadius - product.radius);
                }

                this.particles.push(product);
                this.collected[productType]++;
            }

            startGameLoop() {
                this.gameLoop();
            }
        }

        // 启动游戏
        window.addEventListener('load', () => {
            new Game();
        });
    </script>
</body>
</html>
